package io.noties.markwon.app.samples;

import com.noties.markwon.utils.LogUtils;

import io.noties.markwon.Markwon;
import io.noties.markwon.app.sample.Tags;
import io.noties.markwon.app.sample.ui.MarkwonTextViewSample;
import io.noties.markwon.ext.strikethrough.StrikethroughPlugin;
import io.noties.markwon.sample.annotations.MarkwonArtifact;
import io.noties.markwon.sample.annotations.MarkwonSampleInfo;
import java.util.Collections;
import java.util.WeakHashMap;
import ohos.app.Context;

/**
 * @author: yangrui
 * @function: CacheMarkwonSample
 * @date: 2021/3/23
 */
@MarkwonSampleInfo(
  id = "20200707102458",
  title = "Cache Markwon instance",
  description = "A static cache for `Markwon` instance " +
    "to be associated with a `Context`",
  artifacts = MarkwonArtifact.CORE,
  tags = Tags.cache
)
class CacheMarkwonSample extends MarkwonTextViewSample {

  private final static WeakHashMap cache = (WeakHashMap) Collections.synchronizedMap(new WeakHashMap<Context, Markwon>());

  @Override
  public void render() {
    render("# First!");
    render("## Second!!");
    render("### Third!!!");
  }

  private void render(String md) {
    final Markwon markwon = with(context);
    LogUtils.i("tag", "markwon:" + markwon.hashCode() + ", md:" + md);
    markwon.setMarkdown(textView, md);
  }

  private Markwon with(Context context) {
    // yeah, why work as expected? new value is returned each time, no caching occur
    //  kotlin: 1.3.72
    //  intellij plugin: 1.3.72-release-Studio4.0-5
//      return cache.getOrPut(context) {
//        // create your markwon instance here
//        return Markwon.builder(context)
//          .usePlugin(StrikethroughPlugin.create())
//          .build()
//      }
    if (cache.get(context) != null) {
      return (Markwon) cache.get(context);
    } else {
      Markwon m = Markwon.builder(context)
        .usePlugin(StrikethroughPlugin.create())
        .build();
      cache.put(context, m);
      return m;
    }
  }
}